import uiautomator2 as u2
# 判断元素是否存在
def find_element(connect,**kwarg)->object:
    try:
        element=connect(**kwarg)
        if getattr(element,'info'):
            return element
        else:
            return None
    except u2.exceptions.UiObjectNotFoundError:
        # print(f"Warning:未找到{kwarg}元素")
        return None 
# 判断子元素是否存在 存在则返回
def find_child_element(parent_element,**kwarg)->object:
     try:
          child_element=parent_element.child(**kwarg)
          if getattr(child_element,'info'):
              return child_element
          else:
              return None
     except u2.exceptions.UiObjectNotFoundError:
          return None
# 查找并点击元素，成功返回True,未找到返回False
def click_element(connect,timeout=1,**kwarg)->bool:
    try:
        connect(**kwarg).click(timeout)
        return True
    except u2.exceptions.UiObjectNotFoundError:
        #   print(f"Warning:未找到{kwarg}元素")
          return False


# 获取机器人在群聊的群昵称
def get_rebot_name(connect)->str:
     if not click_element(connect,resourceId="com.tencent.mm:id/fq",className="android.widget.ImageView"):
          return None
     # 滑动
     connect.swipe(400, 1920, 400, 100)
     robot_name_element=find_element(connect,resourceId="android:id/summary",className="android.widget.TextView")
     # 返回
     print(robot_name_element.info)
     if robot_name_element is None:
          click_element(connect,resourceId="com.tencent.mm:id/actionbar_up_indicator_btn",className="android.widget.ImageView")
          return None
     else:
          robot_name=robot_name_element.info['text']
          click_element(connect,resourceId="com.tencent.mm:id/actionbar_up_indicator_btn",className="android.widget.ImageView")
          return robot_name

    